package com.xx.xiawan.videoplayer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.xiaxiang.xiawan.video.VideoInfoListener;
import com.xiaxiang.xiaxwan.ar.data.XXARMaterialVideoData;
import com.xx.xx.videoplayer.R;
//com.xx.xiawan.videoplayer.VideoActivity
public class VideoActivity extends Activity implements View.OnClickListener{


    private static final int MESSAGE_ID_RECONNECTING = 0x01;

    //当前播放的是否为在线直播，如果是，则底层会有一些播放优化
    private static final int IS_LIVE_STREAMING = 0;
    //解码方式，codec＝1，硬解; codec=0, 软解
    private static final int MEDIA_CODEC = 1;

    private MediaController mMediaController;
   // private PLVideoTextureView videoView;
    private Toast mToast = null;
  //  private ProgressBar mLoadingView;
    private boolean mIsActivityPaused = true;
    protected String mVideoPath = null;
    private boolean needResume;
    private int mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_FIT_PARENT; //default
    private int mRotation = 0;
    private XXVideoPlayer mVideoView;
    /*

    private int mRotation = 0;
    private int mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_FIT_PARENT; //default
    */
    /**
     * 视频的方向
     */
    private int mVideoRotation;

    /** 最大声音 */
    private int mMaxVolume;
    /** 当前声音 */
   private int mVolume = -1;
    /** 当前亮度 */
    private float mBrightness = -1f;
    private AudioManager mAudioManager;
    private GestureDetector mGestureDetector;

    private View mVolumeBrightnessLayout;
    private ImageView mOperationBg;
    private ImageView mOperationPercent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        init();
    }

    protected void init(){
        setContentView(R.layout.activity_video);
        initView();
        initVideo();
    }

    protected void initVideo(){
        PLVideoTextureView videoView = (PLVideoTextureView) findViewById(R.id.videoView);
      //  mLoadingView = (ProgressBar) findViewById(R.id.LoadingView);
     //   videoView.setBufferingIndicator(mLoadingView);
        int isLiveStreaming =IS_LIVE_STREAMING;
        mMediaController = new MediaController(this, false, isLiveStreaming == 1);
        videoView.setMediaController(mMediaController);
        mVideoView = new XXVideoPlayer(this);
        mVideoView.setVideoView(videoView);
        mVideoView.setOnInfoListener(mOnInfoListener);
     //   mVolumeBrightnessLayout = findViewById(R.id.operation_volume_brightness);
        mOperationBg = (ImageView) findViewById(R.id.operation_bg);
        mOperationPercent = (ImageView) findViewById(R.id.operation_percent);

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mGestureDetector = new GestureDetector(this, new VideoActivity.MyGestureListener());
        mVideoView.setVideoPath(mVideoPath);
        mVideoView.start();
    }


    protected void initView(){

        /*
        Button btnPlayer = (Button) this.findViewById(R.id.btnPlayer);
        btnPlayer.setOnClickListener(this);
        TextView textView = (TextView)this.findViewById(R.id.tvShare);
        textView.setOnClickListener(this);
        */
        ImageView imgBack = (ImageView)this.findViewById(R.id.imgBack);
        imgBack.setOnClickListener(this);
    }
    @Override
    protected void onPause() {
        super.onPause();
        mToast = null;
        mVideoView.pause();
        mIsActivityPaused = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsActivityPaused = false;
        mVideoView.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoView.stopPlayback();
    }

    public void onClickRotate(View v) {
        mRotation = (mRotation + 90) % 360;
        mVideoView.setDisplayOrientation(mRotation);
    }

    public void onClickSwitchScreen(View v) {
        mDisplayAspectRatio = (mDisplayAspectRatio + 1) % 5;
        mVideoView.setDisplayAspectRatio(mDisplayAspectRatio);
        int ratio = mVideoView.getDisplayAspectRatio();
      //  switch (mVideoView.getDisplayAspectRatio()) {
        switch (ratio) {
            case PLVideoTextureView.ASPECT_RATIO_ORIGIN:
                showToastTips("Origin mode");
                break;
            case PLVideoTextureView.ASPECT_RATIO_FIT_PARENT:
                showToastTips("Fit parent !");
                break;
            case PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT:
                showToastTips("Paved parent !");
                break;
            case PLVideoTextureView.ASPECT_RATIO_16_9:
                showToastTips("16 : 9 !");
                break;
            case PLVideoTextureView.ASPECT_RATIO_4_3:
                showToastTips("4 : 3 !");
                break;
            default:
                break;
        }
    }


    private VideoInfoListener mOnInfoListener = new VideoInfoListener(){

        @Override
        public void onPrepared() {

        }

        @Override
        public void onCompletion() {

        }

        @Override
        public void mediaInfoBufferingStart(int extra) {
            System.out.println("正在缓冲----\"");
            //开始缓存，暂停播放
//                    if (isPlaying()) {
//                        stopPlayer();
            if (mVideoView != null) {
                mVideoView.pause();
            }
            needResume = true;
           // mLoadingView.setVisibility(View.VISIBLE);
        }

        @Override
        public void mediaInfoBufferingEnd(int extra) {
            System.out.println("缓冲完成----");
            //缓存完成，继续播放
            if (needResume)
//                        startPlayer();
                if (mVideoView != null) {
                    mVideoView.start();
                }
          // mLoadingView.setVisibility(View.GONE);
        }

        @Override
        public void mediaInfoRenderingStart(int extra) {
            System.out.println("缓冲完成----");
            //缓存完成，继续播放
            if (needResume)
//                        startPlayer();
                if (mVideoView != null) {
                    mVideoView.start();
                }
         //   mLoadingView.setVisibility(View.GONE);
        }

        @Override
        public void mediaInfoBufferingBytesUpdate(int extra) {

        }

        @Override
        public void doOther(int extra) {
            mVideoRotation=extra;
        }
    };

    private void showToastTips(final String tips) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                }
                mToast = Toast.makeText(VideoActivity.this, tips, Toast.LENGTH_SHORT);
                mToast.show();
            }
        });
    }

    private void sendReconnectMessage() {
        showToastTips("正在重连...");
      //  mLoadingView.setVisibility(View.VISIBLE);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_ID_RECONNECTING), 500);
    }

    protected Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != MESSAGE_ID_RECONNECTING) {
                return;
            }
            if (mIsActivityPaused || !Utils.isLiveStreamingAvailable()) {
                finish();
                return;
            }
            if (!Utils.isNetworkAvailable(VideoActivity.this)) {
                sendReconnectMessage();
                return;
            }
            mVideoView.setVideoPath(mVideoPath);
            mVideoView.start();
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event))
            return true;

        // 处理手势结束
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                endGesture();
                break;
        }

        return super.onTouchEvent(event);
    }

    /** 手势结束 */
    private void endGesture() {
        mVolume = -1;
        mBrightness = -1f;

        // 隐藏
        mDismissHandler.removeMessages(0);
        mDismissHandler.sendEmptyMessageDelayed(0, 500);
    }

    @Override
    public void onClick(View view) {
        onMyClick(view);
    }

    protected void onMyClick(View view){
        int id = view.getId();
        /*
        if(id ==  R.id.btnPlayer){
            pressPlayerBtn();
        }else if(id == R.id.imgBack){
            finish();
        }else if(R.id.tvShare == id){
            startShare();
        }*/
    }
    protected void pressPlayerBtn(){
        startPlayer();
    }

    protected void startPlayer(){

    }

    protected void startShare(){

    }
    private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        /** 双击 */
        @Override
        public boolean onDoubleTap(MotionEvent e) {

            if(mDisplayAspectRatio == PLVideoTextureView.ASPECT_RATIO_FIT_PARENT){
                mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT;
            }else {
                mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_FIT_PARENT;
            }

            if (mVideoView != null) mVideoView.setDisplayAspectRatio(mDisplayAspectRatio);
            return true;
        }

        /** 滑动 */
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            float mOldX = e1.getX(), mOldY = e1.getY();
            int y = (int) e2.getRawY();
            Display disp = getWindowManager().getDefaultDisplay();
            int windowWidth = disp.getWidth();
            int windowHeight = disp.getHeight();

            if (mOldX > windowWidth * 4.0 / 5)// 右边滑动
                onVolumeSlide((mOldY - y) / windowHeight);
            else if (mOldX < windowWidth / 5.0)// 左边滑动
                onBrightnessSlide((mOldY - y) / windowHeight);

            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    }

    /** 定时隐藏 */
    private Handler mDismissHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(mVolumeBrightnessLayout != null){
                mVolumeBrightnessLayout.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 滑动改变声音大小
     *
     * @param percent
     */
    private void onVolumeSlide(float percent) {
        if (mVolume == -1) {
            mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (mVolume < 0)
                mVolume = 0;

            // 显示
            mOperationBg.setImageResource(R.drawable.video_volumn_bg);
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
        }

        int index = (int) (percent * mMaxVolume) + mVolume;
        if (index > mMaxVolume)
            index = mMaxVolume;
        else if (index < 0)
            index = 0;

        // 变更声音
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
        // 变更进度条
        ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
        lp.width = findViewById(R.id.operation_full).getLayoutParams().width
                * index / mMaxVolume;
        mOperationPercent.setLayoutParams(lp);
    }

    /**
     * 滑动改变亮度
     *
     * @param percent
     */
    private void onBrightnessSlide(float percent) {
        if (mBrightness < 0) {
            mBrightness = getWindow().getAttributes().screenBrightness;
            if (mBrightness <= 0.00f)
                mBrightness = 0.50f;
            if (mBrightness < 0.01f)
                mBrightness = 0.01f;

            // 显示
            mOperationBg.setImageResource(R.drawable.video_brightness_bg);
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
        }
        WindowManager.LayoutParams lpa = getWindow().getAttributes();
        lpa.screenBrightness = mBrightness + percent;
        if (lpa.screenBrightness > 1.0f)
            lpa.screenBrightness = 1.0f;
        else if (lpa.screenBrightness < 0.01f)
            lpa.screenBrightness = 0.01f;
        getWindow().setAttributes(lpa);

        ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
        lp.width = (int) (findViewById(R.id.operation_full).getLayoutParams().width * lpa.screenBrightness);
        mOperationPercent.setLayoutParams(lp);
    }

}
